package com.qf.stu.application.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.stu.application.dao.StuDao;
import com.qf.stu.application.entity.Stu;
import com.qf.stu.application.service.StuService;
import com.qf.stu.feign.ClsRemote;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.GlobalTransaction;
import io.seata.tm.api.GlobalTransactionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * (Stu)表服务实现类
 *
 * @author makejava
 * @since 2023-11-15 09:14:19
 */
@Service("stuService")
public class StuServiceImpl extends ServiceImpl<StuDao, Stu> implements StuService {

    @Autowired
    private ClsRemote clsRemote;

    @Override
    @GlobalTransactional
    public boolean save(Stu entity) {
        try {
            //保存学生
            super.save(entity);
            //远程调用保存班级
            clsRemote.insert();
            //抛出异常
            System.out.println(1 / 0);
        } catch (Exception e) {
            e.printStackTrace();
            //执行一些代码
            //手动回滚全局事务
            String xid = RootContext.getXID();
            System.out.println("获取seata的全局事务id：" + xid);
            if (xid != null) {
                //判断是否存在seata的全局事务
                try {
                    //获取全局事务对象
                    GlobalTransaction reload = GlobalTransactionContext.reload(xid);
                    //手动回滚全局事务
                    reload.rollback();
                } catch (TransactionException ex) {
                    System.out.println("获取全局事务" + xid + "失败！" + ex.getMessage());
                }
            }
        }
        return true;
    }
}

